import Vue from 'vue'
import App from './App'
import router from './router'
// 引入UI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// 公共less
import './assets/less/common.less'
// 公共js
import api from './assets/js/common.js'
import './assets/js/jquery.js'
// 交互插件axios
import axios from 'axios'
// 编译IE9+能识别
import 'babel-polyfill';

// 默认请求路径 -- 前缀
axios.defaults.baseURL = 'http://localhost:8080';
//axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//  Vue 使用插件
Vue.use(ElementUI) // -- UI

var loading = null;

// 统一设置请求不成功的方法
axios.interceptors.response.use(response => {
	loading.close();
	if(response.data.code != 200) {
		ElementUI.Notification({
			title: '错误',
			message: response.data.message || '登录已过期，请重新登录',
			type: 'error'
		});
		localStorage.removeItem("loginInfo");
		router.replace({
			path: '/login'
		});
	}
	if(response.data.code != 200) {
		ElementUI.Notification({
			title: '错误',
			message: response.data.message || '请求失败',
			type: 'error'
		});
	}
	return response.data;
}, error => {
	console.log(error);
});

// 统一设置请求前修改参数
axios.interceptors.request.use((config) => {
	loading = api.showLoading();
	const loginInfo = JSON.parse(localStorage.getItem("loginInfo"));
	if(loginInfo && config.method == 'post') {
		config.headers.Authorization = loginInfo.token || '';
	}
	return config;
});

// 路由渲染前动作 -- 判断是否登录
router.beforeEach((to, from, next) => {
	//	const loginInfo = JSON.parse(localStorage.getItem("loginInfo"));
	//	if(to.path.indexOf('login') < 0) {
	//		if(!loginInfo || !loginInfo.loginTime || loginInfo.loginTime < new Date().getTime()) {
	//			localStorage.removeItem("loginInfo");
	//			router.replace({
	//				path: '/login'
	//			});
	//			return;
	//		}
	//	}
	next();
});

Vue.prototype.api = api;
Vue.prototype.$http = axios;

/* eslint-disable no-new */
new Vue({
	el: '#app',
	router,
	template: '<App/>',
	components: {
		App
	}
})